package com.tsy.server.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsy.server.common.PageResult;
import com.tsy.server.system.entity.Organization;
import com.tsy.server.system.entity.UserOrganization;
import com.tsy.server.system.entity.dto.OrganizationDTO;
import com.tsy.server.system.entity.vo.OrganizationVO;
import com.tsy.server.system.mapper.OrganizationMapper;
import com.tsy.server.system.mapper.UserOrganizationMapper;
import com.tsy.server.component.security.SecurityUtils;
import com.tsy.server.system.service.OrganizationService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 组织管理服务实现类
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private UserOrganizationMapper userOrganizationMapper;

    @Override
    @Transactional
    public void createOrganization(OrganizationDTO organizationDTO) {
        // 创建组织
        Organization organization = new Organization();
        organization.setOrgName(organizationDTO.getOrgName());
        organization.setOrgLogo(organizationDTO.getOrgLogo());
        Long currentUserId = SecurityUtils.getCurrentUserId();
        organization.setCreatorId(currentUserId);
        // 六位随机字母和数字组合
        String orgId = RandomStringUtils.random(6, true, true);
        organization.setOrgId(orgId);
        organizationMapper.insert(organization);

        // 创建用户组织关联
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setUserId(currentUserId);
        userOrganization.setOrgId(organization.getId());
        // 创建组织，默认组织加入
        userOrganization.setJoinType("1");
        // 默认管理员角色
        userOrganization.setRoleId(1L);
        userOrganization.setUserOrgName(organizationDTO.getUserOrgName() == null ? SecurityUtils.getCurrentUsername() : organizationDTO.getUserOrgName());
        userOrganizationMapper.insert(userOrganization);
    }

    @Override
    public void joinOrganization(UserOrganization userOrganization) {
        // TODO: 实现用户加入组织逻辑
    }

    @Override
    @Transactional
    public void updateOrganization(OrganizationDTO organizationDTO) {
        if (organizationDTO.getId() == null) {
            throw new RuntimeException("组织ID不能为空");
        }

        Long currentUserId = SecurityUtils.getCurrentUserId();
        Organization selectById = organizationMapper.selectById(organizationDTO.getId());
        if (selectById == null) {
            throw new RuntimeException("组织不存在");
        }

        // 修改用户组织信息
        if (StringUtils.isNotBlank(organizationDTO.getUserOrgName())) {
            userOrganizationMapper.update(null, Wrappers.<UserOrganization>lambdaUpdate()
                    .set(UserOrganization::getUserOrgName, organizationDTO.getUserOrgName())
                    .eq(UserOrganization::getUserId, currentUserId)
                    .eq(UserOrganization::getOrgId, organizationDTO.getId()));
        }

        if (StringUtils.isBlank(organizationDTO.getOrgName()) && StringUtils.isBlank(organizationDTO.getOrgLogo())) {
            return;
        }
        // 判断组织是否自己创建
        if (!selectById.getCreatorId().equals(currentUserId)) {
            throw new RuntimeException("您不是该组织创建者，无法修改组织信息");
        }
        // 修改组织信息
        Organization organization = new Organization();
        organization.setId(organizationDTO.getId());
        organization.setOrgName(organizationDTO.getOrgName());
        organization.setOrgLogo(organizationDTO.getOrgLogo());
        organizationMapper.updateById(organization);

    }

    /**
     * 分页查询用户相关组织，连表填充joinTime和userOrgName
     * @param organizationVO 查询参数
     * @return 分页组织列表
     */
    @Override
    public Page<Organization> getUserOrgList(OrganizationVO organizationVO) {
        Page<Organization> page = PageResult.buildPage();
//        LambdaQueryWrapper<Organization> queryWrapper = Wrappers.lambdaQuery(Organization.class);
//        queryWrapper.orderByDesc(Organization::getUpdateTime);
//        queryWrapper.eq(Organization::getCreatorId, SecurityUtils.getCurrentUserId());
//        queryWrapper.like(StringUtils.isNotBlank(organizationVO.getOrgName()), Organization::getOrgName, organizationVO.getOrgName());
//        return organizationMapper.selectPage(page, queryWrapper);
        Long userId = SecurityUtils.getCurrentUserId();
        return organizationMapper.selectUserOrgPage(page, userId, organizationVO.getOrgName(), organizationVO.getUserOrgName(), organizationVO.getRoleId());
    }

    @Override
    public List<OrganizationVO> getUserOrgs() {
        Long userId = SecurityUtils.getCurrentUserId();
        return organizationMapper.selectUserOrgs(userId);
    }

    @Override
    @Transactional
    public void leaveOrganization(Long orgId) {
        Long currentOrgId = SecurityUtils.getCurrentOrgId();
        if (orgId.equals(currentOrgId)) {
            throw new RuntimeException("不能退出当前组织，请先切换组织");
        }

        Long userId = SecurityUtils.getCurrentUserId();
        LambdaQueryWrapper<UserOrganization> queryWrapper = Wrappers.<UserOrganization>lambdaQuery()
                .eq(UserOrganization::getUserId, userId)
                .eq(UserOrganization::getOrgId, orgId);
        UserOrganization userOrganization = userOrganizationMapper.selectOne(queryWrapper);
        // 如果是管理员退出组织，需要删除组织
        if (userOrganization.getRoleId() == 1L) {
            // 判断改组织下是否有其他用户
            Long count = userOrganizationMapper.selectCount(Wrappers.<UserOrganization>lambdaQuery().
                    eq(UserOrganization::getOrgId, orgId)
                    .ne(UserOrganization::getUserId, userId));

            if (count > 0) {
                throw new RuntimeException("该组织下有其他用户，请先将组织下其他用户移除");
            }
            organizationMapper.deleteById(orgId);
        }
        userOrganizationMapper.delete(queryWrapper);
    }

}